package persistencia;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import negocio.ControlCambio;
import negocio.Login;
import controlador.Sistema;

public class perControlCambio {
	private Sistema sist;
	private int max=0;
	public void insert (ControlCambio cc)
	{
		
		try {
			sist=Sistema.getInstance();
			Connection con=PoolConnection.getPoolConnection().getConnection();
			PreparedStatement ps2=con.prepareStatement("select max(IDCC) from CONTROL_CAMBIO");
			ResultSet rs2=ps2.executeQuery();
			if(rs2.next())
				max=rs2.getInt(1);
			PreparedStatement ps=con.prepareStatement("Insert into CONTROL_CAMBIO values (?,?,?,?,?,?)");
			ps.setInt(1, max+1);
			ps.setInt(2, sist.getLogins().getNroLogin());
			ps.setString(3, cc.getCambio_ant());
			ps.setString(4, cc.getCambio_post());
			ps.setDate(5, (Date) cc.getFecha());
			ps.setString(6, cc.getTabla());
			ps.execute();
			PoolConnection.getPoolConnection().releaseConnection(con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/*-- TABLA CONTROL_CAMBIO
	CREATE TABLE CONTROL_CAMBIO (
	IDCC INT, 
	ID_LOGIN INT, 
	DESCANT TEXT,
	DESPOST TEXT, 
	FECHA DATETIME, 
	TABLA VARCHAR(20), */
	public Vector<ControlCambio> select (String desde, String hasta)
	{
		Vector <ControlCambio> v=new Vector <ControlCambio>();
		try {
			sist=Sistema.getInstance();	
			Login l = null;
			Connection con=PoolConnection.getPoolConnection().getConnection();
			PreparedStatement ps2=con.prepareStatement("select c.ID_LOGIN,c.DESCANT,c.DESPOST,c.FECHA,c.TABLA from CONTROL_CAMBIO c,Logins l where c.FECHA between ? and ?");
			ps2.setString(1, desde);
			ps2.setString(2, hasta);
			ResultSet rs2=ps2.executeQuery();
			while(rs2.next())
			{
				int login=rs2.getInt(1);
				PreparedStatement ps=con.prepareStatement("select * from LOGINS where IDLOGIN =?");
				ps.setInt(1, login);
				ResultSet rs=ps.executeQuery();
				if(rs.next())
				{
					l=new Login();
					l.setUsuario(rs.getString(2));
				}
				ControlCambio cc=new ControlCambio(l, rs2.getString(2), rs2.getString(3), rs2.getString(5),rs2.getDate(4));
				v.add(cc);
			}			
			ps2.execute();
			PoolConnection.getPoolConnection().releaseConnection(con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return v;
		
	}
}
